<template>
  <view class="container">
    <map
      id="map"
      :longitude="mapConfig.longitude"
      :latitude="mapConfig.latitude"
      :scale="mapConfig.scale"
      :markers="mapConfig.markers"
      @markertap="bindmarkertap"
    ></map>
    <view class="map-dialog" v-if="dialogVisible">
      <view class="map-info">
        <view class="map-info-txt">
          <view class="title">{{selectMarker.title}}</view>
          <view class="addr">{{selectMarker.address}}</view>
        </view>
      </view>
      <view class="map-distance">
        距离当前位置：
        <text class="distance">{{distance}}公里</text>
      </view>
      <view class="map-btn" @click="onGuide">开始导航</view>
    </view>
  </view>
</template>

<script>
// 引入SDK核心类，js文件根据自己业务，位置可自行放置
var QQMapWX = require("@/static/qqmap-wx-jssdk.min.js");
var qqmapsdk;
// 测试点
const mapLL = [
  {
    title: "终点",
    longitude: 113.53909,
    latitude: 22.240989
  },
  {
    title: "起点",
    longitude: 113.545044,
    latitude: 22.242078
  }
];
export default {
  data() {
    return {
      mapConfig: {
        longitude: 113.53909, // 中心经度
        latitude: 22.240989, // 中心纬度
        scale: 16, // 缩放级别，取值范围为3-20
        markers: []
      },
      dialogVisible: false,
      selectMarker: {},
      isLocationAuth: false,
      distance: "",
      currentLocation: {},
      mapContext: {}
    };
  },
  onShow() {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: "" // 自己申请的key
    });
    this.mapContext = wx.createMapContext('map', this)
    // this.setMarkers()
    // 获取当年位置
    this.getCurrentLocation()
    this.getHotel();
  },
  methods: {
    // 获取当前位置
    getCurrentLocation(){
      wx.getLocation({
        type: 'wgs84',
        success: (res)=> {
          this.isLocationAuth = true
          const latitude = res.latitude
          const longitude = res.longitude
          this.currentLocation = {latitude,longitude}
        },
        fail:(e)=>{
          this.isLocationAuth = false
        }
      })
    },

    // 利用两地经纬度计算距离
    getkm(form, to) {
      let R=6371.393
      let Pi=Math.PI
      let x1,y1,x2,y2
      x1=form.latitude
      y1=form.longitude
      x2=to.latitude
      y2=to.longitude
      let a=(Math.sin(Pi/180*(y1/2-y2/2)))**2
      let b= Math.cos(y1*Pi/180)*Math.cos(y2*Pi/180)*Math.sin((x1/2-x2/2)*Pi/180)**2
      let L=2*R*Math.asin((a+b)**0.5)
      return Number(L).toFixed(2) || ''
    },

    // 验证是否已授权
    async checkIsLocationAuth() {
      uni.showModal({
        title: '提示',
        content: '检测到您没打开此小程序的定位权限，是否去设置打开？',
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => { }
            })
          } else if (res.cancel) {
            // console.log('用户点击取消');
          }
        }
      });
    },
    // 开始导航
    onGuide() {
      this.mapContext.openMapApp({
        longitude: this.selectMarker.longitude,
        latitude: this.selectMarker.latitude,
        destination: this.selectMarker.title
      })
    },
    // 设置标记点
    setMarkers() {
      mapLL.map(el => {
        this.mapConfig.markers.push({
          title: el.title, // 标题
          longitude: el.longitude,
          latitude: el.latitude,
          iconPath:"/static/location.png", // 图标
          width: 46,
          height: 46
        });
      });
    },
    // 搜索酒店
    getHotel() {
      // 调用接口
      qqmapsdk.search({
        keyword: "酒店",
        location: {
          latitude: this.mapConfig.latitude,
          longitude: this.mapConfig.longitude
        },
        success: res => {
          console.log(res);
          var mks = [];
          for (var i = 0; i < res.data.length; i++) {
            mks.push({
              // 获取返回结果，放到mks数组中
              title: res.data[i].title,
              id: +res.data[i].id,
              latitude: res.data[i].location.lat,
              longitude: res.data[i].location.lng,
              width: 46,
              height: 46,
              iconPath: "/static/location.png", // 图标
              address: res.data[i].address,
              distance: res.data[i]._distance,
              callout: {
                display: "ALWAYS",
                content: res.data[i].title,
                anchorY: 60,
                fontSize: 13,
                bgColor: "none",
                color: "#666666"
              }
            });
          }
          this.mapConfig.markers = mks;
        },
        fail: function(res) {
          console.log(res);
        },
        complete: function(res) {
          console.log(res);
        }
      });
    },
    // 标记点点击
    bindmarkertap(item) {
      console.log("item", item, this.mapConfig.markers);
      const selectMarker = this.mapConfig.markers.filter(
        el => el.id === item.markerId
      );
      if(!this.isLocationAuth){
        this.checkIsLocationAuth()
        return
      }
      // console.log("selectMarker", selectMarker);
      this.dialogVisible = true;
      this.selectMarker = selectMarker[0];
      this.distance = this.getkm({latitude: this.selectMarker.latitude,longitude: this.selectMarker.longitude},this.currentLocation)

    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
}
#map {
  width: 100%;
  height: 100%;
}
.map {
  &-dialog {
    position: fixed;
    bottom: 68rpx;
    left: 50%;
    box-sizing: border-box;
    transform: translateX(-50%);
    width: 686rpx;
    height: 311rpx;
    background-color: #ffffff;
    overflow: hidden;
    border-radius: 20rpx;
    padding: 32rpx 24rpx;
  }

  &-info {
    display: flex;
    &-img {
      width: 200rpx;
      height: 154rpx;
      border-radius: 10rpx;
      background-color: #eee;
      margin-right: 24rpx;
      flex-shrink: 0;
    }
    &-txt {
      overflow: hidden;
      .title {
        color: rgba(51, 51, 51, 1);
        font-size: 36rpx;
        font-weight: 500;
        margin-bottom: 20rpx;
        line-height: 50rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 50rpx;
      }
      .addr {
        color: rgba(153, 153, 153, 1);
        font-size: 30rpx;
        font-weight: 500;
        line-height: 42rpx;
        height: 84rpx;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  &-distance {
    margin-top: 48rpx;
    font-size: 26rpx;
    font-weight: 500;
    color: #999999;
  }

  &-btn {
    position: absolute;
    right: 24rpx;
    bottom: 32rpx;
    width: 192rpx;
    height: 69rpx;
    border-radius: 12rpx;
    background: #06c05f;
    font-size: 32rpx;
    font-weight: 500;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
